package com.douyu.water.core.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.douyu.water.core.PagePara;
import com.douyu.water.core.dao.MenuMapper;
import com.douyu.water.core.dao.RoleMenuMapper;
import com.douyu.water.core.dao.UserMapper;
import com.douyu.water.core.model.Menu;
import com.douyu.water.core.model.MenuExample;
import com.douyu.water.core.model.Role;
import com.douyu.water.core.model.RoleMenuExample;
import com.douyu.water.core.model.RoleMenuKey;
import com.douyu.water.core.model.User;
import com.douyu.water.core.model.UserExample;
import com.douyu.water.util.Func;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private MenuMapper menuMapper;
	@Autowired
	private RoleMenuMapper roleMenuMapper;
	@Override
	public List<User> select(User record, PagePara page) {
		List<User> list = null;
		UserExample example = createExample(record,false);
		if(page != null)
		{
			int total = userMapper.countByExample(example);
			page.setTotal(total);
			example.setPagePara(page);
		}
		example.setOrderByClause(" isort asc,rcdtime desc");
		list = userMapper.selectByExample(example);
		return list;
	}

	@Override
	public int insert(User record) {
		int flag = 0;
		if(record == null || StringUtils.isBlank(record.getUsername()))
		{
			return flag;
		}
		record.setUcode(Func.getNewId());
		record.setRcdtime(new Date());
		record.setPwd("123456");
		flag = userMapper.insert(record);
		return flag;
	}

	@Override
	public int update(User record) {
		int flag = 0;
		if(!checkUser(record))
		{
			return flag;
		}
		record.setRcdtime(new Date());		
		flag = userMapper.updateByPrimaryKeyWithBLOBs(record);
		return flag;
	}

	@Override
	public int updateSelective(User record) {
		int flag = 0;
		if(!checkUser(record))
		{
			return flag;
		}
		flag = userMapper.updateByPrimaryKeySelective(record);
		return flag;
	}

	@Override
	public User view(User record) {
		User user = null;
		if(!checkUser(record))
	    {
			return user;
	    }
		user = userMapper.selectByPrimaryKey(record.getUcode().trim());
		return user;
	}

	@Override
	public int delete(User record) {
		int flag = 0;
		if(!checkUser(record))
		{
			return flag;
		}
		flag = userMapper.deleteByPrimaryKey(record.getUcode().trim());
		return flag;
	}

	@Override
	public User login(User user)
	{
		User login = null;
		if(user == null || StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPwd()))
		{
			return login;
		}
		UserExample example = createExample(user,true);
		User list = userMapper.selectLogin(user);
		if(list == null )
		{
			return login;
		}
		login = list;
		return login;
	}
	
	@Override
	public List<Menu> selectMenu(User login)
	{
		//获取已经分配的功能菜单
		List<Menu> menu = selectParent(login);
		//获取分配的操作
		processMenu(menu);
		return menu;
	}
	
	@Override
	public  void checkRole(List<Role> list, User menu)
	{
		if(menu == null || StringUtils.isBlank(menu.getRole()) || list == null || list.size() ==0)
		{
			return;
		}
		String roles = menu.getRole();
		String[] role_arr = roles.split("[/ ]+");
		List<String> role = new ArrayList<String>();
		for(String role_str : role_arr)
		{
			if(!StringUtils.isBlank(role_str))
			{
				role.add(role_str.trim());
			}
		}
		for(int i = 0;i < list.size();i++)
		{
			Role temp = list.get(i);
			String _role = temp.getUcode();
			if(role.contains(_role.trim()))
			{
				temp.setCheck(true);
			}
			else
			{
				temp.setCheck(false);
			}
		}
	}
	/**
	 * 检索父级菜单
	 * @param login User
	 * @return List<Menu>
	 */
	private List<Menu> selectParent(User login)
	{
		if(login == null || StringUtils.isBlank(login.getUcode()))
		{
			return null;
		}
		String userCode = login.getUcode();		
		List<Menu> list = null;
		if(userCode.trim().equals("1")){
			list = userMapper.selectUserMenu(null);
		}
		else
		{
			List<String> role = createList(login);
			List<String> roleCode = selectRoleMenu(role);
			if(roleCode != null && roleCode.size() > 0)
			{
				Map<String,List<String>> para = new HashMap<String,List<String>>();
				para.put("list",roleCode);
				list = userMapper.selectUserMenu(para);
			}
		}
		return list;
	}
	
	private List<String> selectRoleMenu(List<String> role)
	{
		if(role == null || role.size() == 0)
		{
			return null;
		}
		List<String> list = new ArrayList<String>();
		RoleMenuExample example = new RoleMenuExample();
		RoleMenuExample.Criteria criteria = example.createCriteria();
		criteria.andRolecodeIn(role);
		List<RoleMenuKey> rm = roleMenuMapper.selectByExample(example);
		for(RoleMenuKey rmk : rm)
		{
			list.add(rmk.getMenucode());
		}
		return list;
	}
	/**
	 * 处理菜单获取子菜单
	 * @param list
	 */
	private void processMenu(List<Menu> list)
	{
		if(list == null || list.size() == 0)
		{
			return;
		}
		for(Menu temp : list)
		{
			String menuCode = temp.getUcode();
			List<Menu> child = selectChild(menuCode,"2");
			if(child != null && child.size() > 0)
			{
				temp.setChild(child);
			}
		}
	}
		
	/**
	 * 根据类型检索子菜单或操作
	 * @param parent
	 * @param type
	 * @return
	 */
	private List<Menu> selectChild(String parent,String type)
	{
		List<Menu> child = null;
		MenuExample example = createMenuExample(parent,type);
		child = menuMapper.selectByExample(example);
		return child;
	}
	
	private MenuExample createMenuExample(String parent,String type)
	{
		MenuExample example = new MenuExample();
		MenuExample.Criteria criteria = example.createCriteria();
		if(StringUtils.isBlank(parent))
		{
			criteria.andParentIsNull();
		}
		else
		{
			criteria.andParentEqualTo(parent.trim());
		}
		if(!StringUtils.isBlank(type))
		{
			criteria.andUtypeEqualTo(type.trim());
		}
		return example;
	}
	/**
	 * 角色列表
	 * @param login User
	 * @return List<String>
	 */
	private List<String> createList(User login)
	{
		if(login == null || StringUtils.isBlank(login.getUcode()))
		{
			return null;
		}
		String role = login.getRole();
		if(StringUtils.isBlank(role))
		{
			return null;
		}
		List<String> role_list = new ArrayList<String>();
		String[] roles = role.split("[, ]+");
		for(String str : roles)
		{
			if(!StringUtils.isBlank(str))
			{
			  role_list.add(str);	
			}
		}
		return role_list;
	}
	/**
	 * 检测用户是否合法
	 * @param record
	 * @return
	 */
	private boolean checkUser(User record)
	{
		boolean flag = true;
		if(record == null || StringUtils.isBlank(record.getUcode()))
		{
			flag = false;
		}
		return flag;
	}
	/**
	 * 形成检索条件
	 * @param record User
	 * @return
	 */
	private UserExample createExample(User record,boolean login)
	{
		UserExample example = new UserExample();
		UserExample.Criteria criteria = example.createCriteria();
		if(record != null)
		{
			if(!StringUtils.isBlank(record.getUcode()))
			{
				criteria.andUcodeEqualTo(record.getUcode().trim());
			}
			criteria.andUcodeNotEqualTo("1");
			if(!StringUtils.isBlank(record.getUsername()))
			{
				if(login)
				{
					criteria.andUsernameEqualTo(record.getUsername().trim());
				}
				else{
					criteria.andUsernameLike("%" + record.getUsername().trim() + "%");	
				}				
			}
			if(!StringUtils.isBlank(record.getPwd()))
			{
				criteria.andPwdEqualTo(record.getPwd().trim());
			}
			if(!StringUtils.isBlank(record.getPhone()))
			{
				criteria.andPhoneLike("%" + record.getPhone().trim() + "%");
			}
			if(!StringUtils.isBlank(record.getRealname()))
			{
				criteria.andRealnameLike("%" + record.getRealname().trim() + "%");
			}
			if(!StringUtils.isBlank(record.getUnitname()))
			{
				criteria.andUnitnameLike("%" + record.getUnitname() + "%");
			}
		}
		return example;
	}
}
